class RemarksController < ApplicationController
  before_filter:authenticate_user!
  
  # GET /remarks
  # GET /remarks.json
  def index
    @remarks = Remark.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @remarks }
    end
  end

  # GET /remarks/1
  # GET /remarks/1.json
  def show
    @remark = Remark.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @remark }
    end
  end

  # GET /remarks/new
  # GET /remarks/new.json
  def new
    @remark = Remark.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @remark }
    end
  end

  # GET /remarks/1/edit
  def edit
    @remark = Remark.find(params[:id])
  end

  # POST /remarks.js
  def create
    @remark = Remark.new(params[:remark])
    @really_submit = params[:really_submit] != ''
    @topic = Topic.find(params[:remark][:topic_id])

    @remark.author = current_user
    if !@remark.remark_type_allowed?(@remark.remark_type)
      puts "check_remark_type failed!"
      @remark.remark_type = ''
    end
    if @remark.remark_type.can_have_question_version? && !params[:question_version].nil?
      @remark.get_question_version.update_from_params(params[:question_version], false)
      @remark.question_version.author = @remark.author
      if @really_submit && !@remark.question_version.save
        @really_submit = false
      end
    end

    if @remark.remark_type == 'confirm' && @really_submit
      @remark.topic.topic_container.commit_suggestion(@remark.parent_remark.question_version)
    end
    if @really_submit
      @remark.save
      # send_notifications @remark
    end
    respond_to do |format|
      format.js
    end
  end

  # PUT /remarks/1.js
  def update
    @remark = Remark.find(params[:id])
    @really_submit = params[:really_submit] != ''
    if @really_submit
      @remark.update_attributes(params[:remark])
    end
    # if @remark.remark_type == 'suggestion' && !params[:question_version].nil?
    #   @remark.get_question_version.update_from_params(params[:question_version], @really_submit)
    #   @remark.question_version.author = @remark.author
    # end
    respond_to do |format|
      format.js
    end
  end

  # DELETE /remarks/1
  # DELETE /remarks/1.json
  def destroy
    @remark = Remark.find(params[:id])
    @remark.destroy

    respond_to do |format|
      format.html { redirect_to remarks_url }
      format.json { head :no_content }
    end
  end
end
